package com.hxzy.config;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.hxzy.controller.admin.interceptor.AdminLoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.*;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class MvcConfig  extends WebMvcConfigurationSupport {
    @Autowired
    private AdminLoginInterceptor adminLoginInterceptor;

    @Value(value = "${mall.imageserverpath}")
    private String imageServerPath;

    @Value(value = "${mall.imageserver}")
    private String imageServerUrl;

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter fastConverter=new FastJsonHttpMessageConverter();
        //中文乱码的问题
        List<MediaType> types = new ArrayList<MediaType>();
        types.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(types);
        fastConverter.setDefaultCharset(Charset.forName("UTF-8"));

        converters.add(fastConverter);

        //5、追加默认转换器
        super.addDefaultHttpMessageConverters(converters);
    }


    //静态资源放行
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");

        registry.addResourceHandler(imageServerUrl+"/**").addResourceLocations("file:///"+imageServerPath);
    }



    //拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

      registry.addInterceptor(adminLoginInterceptor)
               .addPathPatterns("/admin/**")
               .excludePathPatterns("/admin/login","/admin/logout");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry
                // 本个项目提供的所有的url地址都可以放行
                .addMapping("/**")
                // 允许所有的域名访问
                .allowedOriginPatterns("*")
                //公共访问的请求方式
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                //访问站网是否允许携带其它数据( cookie)
                .allowCredentials(true)
                //两次请求缓存时间(1分钟)
                .maxAge(3600);
    }

}
